/**
 * Copyright(c) kyle.
 */
package org.example.metrics;

import com.codahale.metrics.CachedGauge;
import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;

import java.util.concurrent.TimeUnit;

import static java.util.concurrent.ThreadLocalRandom.current;

/**
 * 对数据的实时性要求没那么高
 *
 * @author kyle
 * @version 1.00.00
 * @updateUser [Kyle]
 * @updateRemark [说明本次修改内容]
 * @date [2021-09-21 12:51]
 * @since [2021-09-21 12:51]
 */
public class CachedGaugeExample {
    public static final MetricRegistry registry = new MetricRegistry();
    public static final Meter totalMeter = new Meter();
    public static final Meter successMeter = new Meter();
    public static final //定义运行的相关参数
            ConsoleReporter reporter = ConsoleReporter.forRegistry(registry)
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.SECONDS)
            .build();

    public static void main(String[] args) throws InterruptedException {
        reporter.start(10, TimeUnit.SECONDS);
        registry.gauge("cached-db-size", () -> new CachedGauge<Long>(30, TimeUnit.SECONDS) {

            @Override
            protected Long loadValue() {
                return business();
            }
        });
        Thread.currentThread().join();
    }

    private static Long business() {
        System.out.println("====business===");
        return System.currentTimeMillis();
    }

    private static void randomSleep() {
        try {
            TimeUnit.SECONDS.sleep(current().nextInt(6));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
